﻿Imports System.Text
Imports Framework.Data

Public Class SettingsControl
    Implements Framework.Settings.ISettingsControl

    Private Sub btnBrowseForFolder_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBrowseForFolder.Click
        Try
            FolderBrowserDialog1.RootFolder = System.Environment.SpecialFolder.MyComputer

            Dim strCurrentPath As String = txtIncomingFilesDirectory.Text
            While Not String.IsNullOrEmpty(strCurrentPath) AndAlso Not IO.Directory.Exists(strCurrentPath)
                strCurrentPath = IO.Path.GetDirectoryName(strCurrentPath)
            End While
            FolderBrowserDialog1.SelectedPath = strCurrentPath
            FolderBrowserDialog1.ShowNewFolderButton = True
            FolderBrowserDialog1.Description = "Select root folder for your share"
            Select Case FolderBrowserDialog1.ShowDialog(Me)
                Case Windows.Forms.DialogResult.OK
                    txtIncomingFilesDirectory.Text = FolderBrowserDialog1.SelectedPath
            End Select
        Catch ex As Exception
            Framework.Misc.HandleException(Me, ex)
        End Try
    End Sub

    Public Sub LoadSettings() Implements Framework.Settings.ISettingsControl.LoadSettings
        txtIncomingFilesDirectory.Text = Settings.IncomingFilesDirectory
        nudPauseAt.Value = CInt(Settings.PauseDownloadingBelowVolumeBytesFree / 1024 / 1024)
        nudRecycleAt.Value = CInt(Settings.RecycleBelowVolumeBytesFree / 1024 / 1024)
        Settings.IncomingDownloadsGrantedToSecurityGroupIds()
        For Each clsGroup As Entities.SecurityGroup In Framework.Security.Manager.GetAllByIds(Settings.IncomingDownloadsGrantedToSecurityGroupIds)
            UpdateGroup(clsGroup, True)
        Next
        AddHandler Framework.Security.Manager.UpdatedGUI, AddressOf EventHandler_GroupUpdated
    End Sub
    Private Sub UpdateGroup(ByVal group As Entities.SecurityGroup, ByVal addIfMissing As Boolean)
        Dim strKey As String = group.Id.ToString
        If lvwDownloadGrantedGroups.Items.ContainsKey(strKey) Then
            With lvwDownloadGrantedGroups.Items(strKey)
                .Text = group.Name
                .Tag = group
            End With
        ElseIf addIfMissing Then
            With lvwDownloadGrantedGroups.Items.Add(strKey, group.Name, CStr(Nothing))
                .Tag = group
            End With
        End If
    End Sub
    Private Sub EventHandler_GroupUpdated(ByVal group As Entities.SecurityGroup)
        Try
            UpdateGroup(group, False)
        Catch ex As Exception
            Framework.Misc.HandleException(Me, ex)
        End Try
    End Sub

    Public Function NeedsSave() As Boolean Implements Framework.Settings.ISettingsControl.NeedsSave
        If txtIncomingFilesDirectory.Text <> Settings.IncomingFilesDirectory Then Return True
        If nudPauseAt.Value * 1024 * 1024 <> Settings.PauseDownloadingBelowVolumeBytesFree Then Return True
        If nudRecycleAt.Value * 1024 * 1024 <> Settings.RecycleBelowVolumeBytesFree Then Return True
        Dim aNewGroups As HashSet(Of Integer) = GetSecurityGroups()
        For Each iId As Integer In Settings.IncomingDownloadsGrantedToSecurityGroupIds
            If Not aNewGroups.Contains(iId) Then Return True
        Next
        If aNewGroups.Count <> Settings.IncomingDownloadsGrantedToSecurityGroupIds.Count Then Return True
        Return False
    End Function

    Public Sub SaveSettings(ByVal transactionScope As TransactionScope) Implements Framework.Settings.ISettingsControl.SaveSettings
        Settings.SetIncomingFilesDirectory(txtIncomingFilesDirectory.Text, transactionScope)
        Settings.SetPauseDownloadingBelowVolumeBytesFree(CLng(nudPauseAt.Value) * 1024 * 1024, transactionScope)
        Settings.SetRecycleBelowVolumeBytesFree(CLng(nudRecycleAt.Value) * 1024 * 1024, transactionScope)
        Settings.SetIncomingDownloadsGrantedToSecurityGroupIds(GetSecurityGroups, transactionScope)
    End Sub

    Public Function GetUserControl() As System.Windows.Forms.UserControl Implements Framework.Settings.ISettingsControl.GetUserControl
        Return Me
    End Function

    Private mIgnoreThresholdAnomily As Boolean = False
    Public Sub ValidateSettings(ByVal errorProvider As Framework.ErrorHandling.ErrorProviderEx) Implements Framework.Settings.ISettingsControl.ValidateSettings
        If Not IO.Directory.Exists(txtIncomingFilesDirectory.Text) Then
            errorProvider.AddError(txtIncomingFilesDirectory, "Invalid directory!")
            txtIncomingFilesDirectory.Focus()
        End If
        Dim blnRecycleChanged As Boolean = (nudRecycleAt.Value * 1024 * 1024 <> Settings.RecycleBelowVolumeBytesFree)
        Dim blnPauseChanged As Boolean = (nudPauseAt.Value * 1024 * 1024 <> Settings.PauseDownloadingBelowVolumeBytesFree)

        If Not mIgnoreThresholdAnomily AndAlso (blnRecycleChanged Or blnPauseChanged) AndAlso nudRecycleAt.Value < nudPauseAt.Value AndAlso nudRecycleAt.Value <> 0 Then
            Select Case MessageBox.Show(Me, "Recycle threshold is lower than pause threshold! It this really what you want?", "FileShare", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
                Case DialogResult.Yes
                    mIgnoreThresholdAnomily = True
                Case Else
                    errorProvider.AddError(nudRecycleAt, "Threshold is lower that pause threshold!")
                    nudRecycleAt.Focus()
            End Select
        End If
    End Sub

    Public Sub SaveCompleted() Implements Framework.Settings.ISettingsControl.SaveCompleted
    End Sub

    Public ReadOnly Property DisplayName() As String Implements Framework.Settings.ISettingsControl.DisplayName
        Get
            Return "File Sharing"
        End Get
    End Property

    Public ReadOnly Property Key() As String Implements Framework.Settings.ISettingsControl.Key
        Get
            Return "FileShare"
        End Get
    End Property

    Public Sub AfterClose() Implements Framework.Settings.ISettingsControl.AfterClose
        RemoveHandler Framework.Security.Manager.UpdatedGUI, AddressOf EventHandler_GroupUpdated
    End Sub

    Public Sub BeforeShow() Implements Framework.Settings.ISettingsControl.BeforeShow

    End Sub

    Private Sub btnAddGroup_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddGroup.Click
        Try
            Dim clsOpts As New Framework.Security.SelectGroupOptions
            clsOpts.Caption = "Select group(s) to grant access to your downloads"
            clsOpts.MultiSelect = True
            clsOpts.HideSecurityGroupIds = GetSecurityGroups()
            For Each clsGroup As Entities.SecurityGroup In Framework.Security.Manager.SelectGroups(Me.FindForm, clsOpts)
                UpdateGroup(clsGroup, True)
            Next
        Catch ex As Exception
            Framework.Misc.HandleException(Me, ex)
        End Try
    End Sub
    Private Function GetSecurityGroups() As Generic.HashSet(Of Integer)
        Dim aRet As New Generic.HashSet(Of Integer)
        For Each clsItem As ListViewItem In lvwDownloadGrantedGroups.Items
            aRet.Add(CType(clsItem.Tag, Entities.SecurityGroup).Id)
        Next
        Return aRet
    End Function

    Private Sub btnRemoveGroup_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRemoveGroup.Click
        Try
            While lvwDownloadGrantedGroups.SelectedItems.Count > 0
                lvwDownloadGrantedGroups.SelectedItems.Item(0).Remove()
            End While
        Catch ex As Exception
            Framework.Misc.HandleException(Me, ex)
        End Try
    End Sub

    Public ReadOnly Property DisplayImage() As System.Drawing.Image Implements Framework.Settings.ISettingsControl.DisplayImage
        Get
            Return My.Resources.Share.ToBitmap
        End Get
    End Property
End Class
